package huu.phong.googlemusic.api;

import huu.phong.googlemusic.model.AllTracks;
import huu.phong.googlemusic.model.Song;
import huu.phong.googlemusic.model.SongUrl;
import huu.phong.googlemusic.utils.Google;

import java.io.IOException;
import java.io.OutputStream;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.google.gson.Gson;

public class GoogleMusicAPI implements IGoogleMusicAPI{

	private String authorizationToken;
	private String cookie;
	private Gson gson;
	
	public GoogleMusicAPI(){
		CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
		gson = new Gson();
	}
	
	@Override
	public void login(String email, String password) throws LoginException, IOException {
		try {
			authorizationToken = Google.getAuthLogin(email, password);
		} catch (IOException e) {
			throw new LoginException();
		}
		cookie = Google.getCookie(authorizationToken);
	}

	@Override
	public List<Song> getAllSongs() throws IOException, URISyntaxException {
		AllTracks all = getAllTracks("");
		List<Song> songs = all.getPlaylist();
		while (!Google.isNullOrEmpty(all.getContinuationToken())){
			all = getAllTracks(all.getContinuationToken());
			songs.addAll(all.getPlaylist());
		}
		return songs;
	}
	
	private AllTracks getAllTracks(String continuationToken) throws IOException{
		URL url = new URL(IGoogleMusicAPI.HTTPS_PLAY_GOOGLE_COM_MUSIC_SERVICES_LOADALLTRACKS + String.format(IGoogleMusicAPI.COOKIE_FORMAT, cookie));
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestProperty(IGoogleMusicAPI.GOOGLE_LOGIN_AUTH_KEY, String.format(IGoogleMusicAPI.GOOGLE_LOGIN_AUTH_VALUE, authorizationToken));
		connection.setRequestMethod("POST");
		connection.setDoOutput(true);
		Map<String, String> fields = new HashMap<String, String>();
		fields.put("json", String.format("{\"continuationToken\":\"%s\"}", continuationToken));
		FormBuilder form = new FormBuilder();
		form.addFields(fields);
		form.close();
		connection.setRequestProperty("Content-Type", form.getContentType());
		OutputStream out = connection.getOutputStream();
		out.write(form.getBytes());
		out.flush();
		AllTracks all = gson.fromJson(Google.streamToString(connection.getInputStream()), AllTracks.class);
		return all;
	}

	@Override
	public String getSongURL(Song song) throws URISyntaxException, IOException {
		URL url = new URL(String.format(IGoogleMusicAPI.HTTPS_PLAY_GOOGLE_COM_MUSIC_PLAY_SONGID, song.getId()));
		URLConnection connection = url.openConnection();
		connection.setRequestProperty(IGoogleMusicAPI.GOOGLE_LOGIN_AUTH_KEY, String.format(IGoogleMusicAPI.GOOGLE_LOGIN_AUTH_VALUE, authorizationToken));
		String response = Google.streamToString(connection.getInputStream());
		return gson.fromJson(response, SongUrl.class).getUrl();
	}
}
